/*
 * BaseCallBack.java
 * business
 *
 * Created by ChenTao on 2017/3/7.
 *
 * Copyright (c) 2017年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.data.net;

import android.content.Context;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.lzy.okgo.callback.AbsCallback;
import com.yidiandao.business.constant.ServerCode;
import com.yidiandao.business.data.net.exception.BizErrorHelper;
import com.yidiandao.business.data.net.exception.BizErrorInfo;
import com.yidiandao.business.data.net.exception.NetErrorHelper;
import com.yidiandao.business.data.net.exception.NetErrorInfo;
import com.yidiandao.business.utils.GsonProvider;
import com.yidiandao.business.utils.JumpUtils;
import com.yidiandao.business.utils.UIUtils;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 网络回掉，顶层
 * <p>
 * <p>Created by ChenTao(chentao7v@gmail.com) on 2017/3/7 16:23
 */
public class BaseCallBack<T extends BaseResponse> extends AbsCallback<T> {

    private Context mContext;

    private BaseRequest mRequest;

    private String mResponseBody;

    private Class<T> mResponseClazz;

    private NetListener<T> mNetListener;

    private String mUrl;

    private Gson mGson;

    public BaseCallBack(BaseRequest request, Class<T> responseClazz, NetListener<T> netListener) {
        mContext = UIUtils.getContext();
        mRequest = request;
        mResponseClazz = responseClazz;
        mNetListener = netListener;
        mGson = GsonProvider.getGson();
        mUrl = request.getUrl();
    }

    @Override
    public void onSuccess(T response, Call call, Response okHttpResponse) {

        // 业务相关错误与成功
        int code = response.getCode();

        if (code == ServerCode.SUCCESS) {
            // 接口访问成功
            if (mNetListener != null) {
                try {
                    mNetListener.onSuccess(response);
                } catch (NullPointerException e) {
                    // 做一个 null 的保护
                    NetErrorInfo errorInfo = new NetErrorInfo(e.getMessage(), ServerCode.NULL, e);
                    mNetListener.onError(errorInfo);
                    NetErrorHelper.reportError(BaseCallBack.class, mUrl, mRequest, errorInfo, null);
                }
            }
        } else {
            // 业务错误封装
            BizErrorInfo bizErrorInfo = BizErrorHelper.generateBizErrorInfo(response);

            String message;
            if (code == ServerCode.INVALID_TOKEN || code == ServerCode.MULTI_DEVICE_LOGIN) {
                // Token失效 --> 跳到登陆页面
                message = bizErrorInfo.getMessage();
                JumpUtils.toLoginActivity(mContext);
            } /*else if (code == ServerCode.MULTI_DEVICE_LOGIN) {
                // 多设备登录,弹出对话框
                message = bizErrorInfo.getMessage();
                showRequireLoginDialog(message);
            }*/ else {
                // 针对接口访问失败的情况,直接读取后台提示信息
                message = bizErrorInfo.getMessage();
            }

            if (mNetListener != null) {
                if (mNetListener.onFailed(bizErrorInfo)) {
                    // 提示用户业务错误 --> 打印到控制台的是全面的信息
                    UIUtils.showToast(message);
                }
            }

            // 打印错误到控制台,并上传部分错误(缺少参数)到Bugly
            BizErrorHelper.reportError(BaseCallBack.class, mUrl, mRequest, bizErrorInfo);
        }
    }

    @Override
    public T convertSuccess(Response response) throws Exception {
        mResponseBody = response.body().string();
        if (TextUtils.isEmpty(mResponseBody)) {
            throw new NullPointerException();
        }

        // 此处Json可能出现转换错误
        return mGson.fromJson(mResponseBody, mResponseClazz);
    }

    @Override
    public void onAfter(T t, Exception e) {
        if (mNetListener != null) {
            mNetListener.onFinal();
        }
    }

    @Override
    public void onError(Call call, Response response, Exception e) {

        // 网络相关错误(无网络连接，Json转换异常等) 处理
        // 包括上传友盟,前台打印错误信息

        // 网络错误封装
        NetErrorInfo netErrorInfo = NetErrorHelper.generateNetErrorInfo(e);

        if (mNetListener != null) {
            if (mNetListener.onError(netErrorInfo)) {
                // 取消的请求不给提示信息
                // 给用户友好提示
                UIUtils.showToast(netErrorInfo.getMessage());
            }
        }

        // 打印错误到控制台,并上传部分错误到友盟
        NetErrorHelper.reportError(BaseCallBack.class, mUrl, mRequest, netErrorInfo, mResponseBody);
    }

//    /** 显示已在其他设备登录，自动退出的对话框 */
//    private void showRequireLoginDialog(String message) {
//
//        final Activity topActivity = ActivityStack.getTopActivity();
//        if (topActivity == null) {
//            return;
//        }
//
//        // 判断强制登录对话框是否正在显示
//        if (BusinessApplicationLike.isShowLogoutDialog) {
//            return;
//        }
//        // 设置正在显示被挤下线的对话框
//        BusinessApplicationLike.isShowLogoutDialog = true;
//
//        BusinessDialog dialog = new BusinessDialog.Builder(topActivity).setTitle(message)
//                .setContentGravity(Gravity.LEFT)
//                .setPositiveButton(R.string.login_again, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        LoginActivity.actionStart(topActivity);
//                    }
//                })
//                .create();
//        dialog.show();
//        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
//            @Override
//            public void onDismiss(DialogInterface dialog) {
//                // 需要强制刷新所有价格相关接口
//                new UserModel().clearUserInfo(true);
//
//                // 重置标记
//                BusinessApplicationLike.isShowLogoutDialog = false;
//            }
//        });
//    }
}
